package ace.module.oauth2.server.core.impl.dao.aggregate.impl;

import ace.module.oauth2.server.core.impl.dao.aggregate.Oauth2AuthorizationAggregate;
import ace.module.oauth2.server.core.impl.dao.entity.Oauth2Authorization;
import ace.module.oauth2.server.core.impl.dao.entity.QOauth2Authorization;
import ace.module.oauth2.server.core.impl.dao.repository.Oauth2AuthorizationRepository;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
* 客户端认证的令牌 aggregate implement.
*
* @author Caspar
*/
@Slf4j
@AllArgsConstructor
@Component
public class Oauth2AuthorizationAggregateImpl implements Oauth2AuthorizationAggregate {
  private final Oauth2AuthorizationRepository oAuth2AuthorizationRepository;

  @Override
  public Oauth2Authorization
      getByRefreshTokenValueOrAccessTokenValueOrAuthorizationCodeValueOrState(String token) {
    QOauth2Authorization qoauth2Authorization = QOauth2Authorization.oauth2Authorization;
    Predicate predicate =
        ExpressionUtils.anyOf(
            qoauth2Authorization.refreshTokenValue.eq(token),
            qoauth2Authorization.accessTokenValue.eq(token),
            qoauth2Authorization.authorizationCodeValue.eq(token),
            qoauth2Authorization.state.eq(token));
    return this.oAuth2AuthorizationRepository.findOne(predicate).orElse(null);
  }
}
